package org.example.security.auth.config.authorize;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

import javax.annotation.Resource;

/**
 * 用于高度信任的应用
 */
@EnableAuthorizationServer
//@Configuration
public class AuthorizationServerConfigUsePassword extends AuthorizationServerConfigurerAdapter {

    @Resource
    @Lazy
    private PasswordEncoder passwordEncoder;

    @Resource
    private AuthenticationManager authenticationManagerBean;

    @Resource
    private UserDetailsService userDetailsService;

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许表单认证
        security.allowFormAuthenticationForClients();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 密码模式需要配置
        endpoints.authenticationManager(authenticationManagerBean)
                // token存储策略
                .tokenStore(tokenStore())
                .reuseRefreshTokens(false)
                .userDetailsService(userDetailsService)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        /*
            密码模式：password
            http://localhost:8080/oauth/token?username=admin&password=admin&grant_type=password&client_id=client&client_secret=123456&scope=all
         */

        clients.inMemory()
                .withClient("client")
                .secret(passwordEncoder.encode("123456"))
                .redirectUris("http://www.baidu.com")
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(86400)
                .scopes("all")
                .authorizedGrantTypes("password", "refresh_token");
    }

}
